package com.logicwin.aibala.ui.screens.screenmain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logicwin.aibala.Aibala;
import com.logicwin.aibala.Main;
import com.logicwin.aibala.R;
import com.logicwin.aibala.action.DownloadSoftwareAction;
import com.logicwin.aibala.action.LoadListAction;
import com.logicwin.aibala.action.LoadStartUpAction;
import com.logicwin.aibala.model.androidSWInfo.APKListItem;
import com.logicwin.aibala.model.androidSWInfo.AndroidSWInfoService;
import com.logicwin.aibala.services.file.FileConnection;
import com.logicwin.aibala.ui.screens.Screen;
import com.logicwin.aibala.utils.MyLog;

import android.os.AsyncTask;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AbsListView.OnScrollListener;

public class ScreenHome extends Screen implements OnTouchListener,
		OnGestureListener {
	/* private ApkPackageAdapter mHomeAdapter; */
	private static String TAG = Main.class.getCanonicalName();
	
	public static int getViewCount = 0;
	
	public static Handler messageHandler;
	
	private final int BTN_INDEX = 0;
	private final int BTN_GAME = 1;
	private final int BTN_ENTER = 2;
	private final int BTN_SNS = 3;
	private final int BTN_MEDIA = 4;
	private final int BTN_OFFICE = 5;
	private final int BTN_SYS = 6;

	private final int MENU_BTN_CONFIG = 0;
	private final int MENU_BTN_DOWNLOAD = 1;
	private final int MENU_BTN_MESSAGE = 2;
	private final int MENU_BTN_REFRESH = 3;
	private final int MENU_BTN_SEARCH = 4;
	
	private final int DIALOG_FILTER = 1;

	private GestureDetector mGestureDetector;
	private int mCurrIndex = 0;
	
	public static String mCurrentType;
	public static String mCurrentSort;

	private ViewFlipper mViewFlipper;
	private HorizontalScrollView mNavigateButtons;
	private ImageButton mButton_Home;
	private ImageButton mButton_Games;
	private ImageButton mButton_Business;
	private ImageButton mButton_Life;
	private ImageButton mButton_Sociality;
	private ImageButton mButton_System;
	private ImageButton mButton_Entertainment;

	public static ScreenHome mContext;
//	public ListView mListHome;
//	public ListView mListGames;
//	public ListView mListEntertainment;
//	public ListView mListSociality;
//	public ListView mListLife;
//	public ListView mListBusiness;
//	public ListView mListSystem;
	public Handler mHandler = new Handler();

	private final int BUTTON_NEW = 0;
	private final int BUTTON_BEST = 1;
	private final int BUTTON_RANK = 2;
	
	public static Map<String,ListView> mViewMap = new HashMap<String,ListView>();

	public ScreenHome() {
		super(SCREEN_TYPE.HOME_T, ScreenHome.class.getCanonicalName());
		// TODO Auto-generated constructor stub
		mContext = this;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Aibala.setCurrentContext(this);
		Looper looper = Looper.myLooper();
        messageHandler = new MessageHandler(looper);
		setContentView(R.layout.screen_home);
		try {
			mCurrentType = AndroidSWInfoService.CLASS_ID_INDEX;
			mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			InitViewFlipper();
			InitScrollViewButton();
			mContext = this;
		} catch (Exception e) {
			Log.i("ScreenHome", e.toString());
		}

	}

	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_FILTER:

			LayoutInflater inflater = LayoutInflater.from(this);
			final View textEntryView = inflater.inflate(R.layout.second_filter,
					null);
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setView(textEntryView);
			ListView listView = (ListView) textEntryView
					.findViewById(R.id.filter_list);
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("filter_name", "test1");
			map.put("filter_count", "1232 >");
			list.add(map);
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("filter_name", "test2");
			map1.put("filter_count", "132 >");
			list.add(map1);
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("filter_name", "test3");
			map2.put("filter_count", "12 >");
			list.add(map2);

			SimpleAdapter adapter = new SimpleAdapter(this, list,
					R.layout.filter_item, new String[] { "filter_name",
							"filter_count" }, new int[] { R.id.filter_name,
							R.id.filter_count });

			listView.setAdapter(adapter);

			listView.setOnItemClickListener(new FilterListener(new String[]{"test1","test2","test3"}));
			return builder.create();
		}
		return null;
	}
	public Handler getHandler(){
		return mHandler;
	}	
	private void setListView(ListView view, ListViewScrollListener listener,
			ApkPackageAdapter adapter) {
		view.setAdapter(adapter);
		view.setOnItemClickListener(adapter);
		// view.setOnItemClickListener(clictlistener);
		view.setOnScrollListener(listener);
	}

	
	private void InitViewFlipper() {
		mNavigateButtons = (HorizontalScrollView) findViewById(R.id.navigate_view);

		mViewFlipper = (ViewFlipper) findViewById(R.id.flipper);

		ListView listView = (ListView)findViewById(R.id.listview_home);
		setListView(
				listView,
				new ListViewScrollListener(BTN_INDEX),
				new ApkAdapterIndex(this, AndroidSWInfoService.getAndroidSWList(
						AndroidSWInfoService.CLASS_ID_INDEX,
						AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_INDEX,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_INDEX, listView);
		setGestureListener(listView);
		 
		listView = (ListView) findViewById(R.id.listview_games);
		setListView(
				listView,
				new ListViewScrollListener(BTN_GAME),
				new ApkAdapterGame(this, AndroidSWInfoService
						.getAndroidSWList(AndroidSWInfoService.CLASS_ID_GAME,
								AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_GAME,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_GAME, listView);
		 
		listView = (ListView) findViewById(R.id.listview_entertainment);
		setListView(
				listView,
				new ListViewScrollListener(BTN_ENTER),
				new ApkAdapterEnter(this, AndroidSWInfoService
						.getAndroidSWList(AndroidSWInfoService.CLASS_ID_ENTER,
								AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_ENTER,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_ENTER, listView);

		listView = (ListView) findViewById(R.id.listview_sociality);
		setListView(
				listView,
				new ListViewScrollListener(BTN_SNS),
				new ApkAdapterSns(this, AndroidSWInfoService
						.getAndroidSWList(AndroidSWInfoService.CLASS_ID_SNS,
								AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_SNS,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_SNS, listView);

		listView = (ListView)findViewById(R.id.listview_life);
		setListView(
				listView,
				new ListViewScrollListener(BTN_MEDIA),
				new ApkAdapterMedia(this, AndroidSWInfoService.getAndroidSWList(
						AndroidSWInfoService.CLASS_ID_MEDIA,
						AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_MEDIA,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_MEDIA, listView);
		
		listView = (ListView) findViewById(R.id.listview_business);
		setListView(
				listView,
				new ListViewScrollListener(BTN_OFFICE),
				new ApkAdapterOffice(this, AndroidSWInfoService
						.getAndroidSWList(AndroidSWInfoService.CLASS_ID_OFFICE,
								AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_OFFICE,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_OFFICE, listView);
		 
		listView = (ListView) findViewById(R.id.listview_system);
		setListView(
				listView,
				new ListViewScrollListener(BTN_SYS),
				new ApkAdapterSys(this, AndroidSWInfoService
						.getAndroidSWList(AndroidSWInfoService.CLASS_ID_SYS,
								AndroidSWInfoService.SORT_ID_BEST, 0),AndroidSWInfoService.CLASS_ID_SYS,AndroidSWInfoService.SORT_ID_BEST));
		mViewMap.put(AndroidSWInfoService.CLASS_ID_SYS, listView);
		
		int[][] flipperId = new int[][] {
				{ R.id.second_home_buttons, R.id.second_home_button_best,
						R.id.second_home_button_new,
						R.id.second_home_button_rank },
				{ R.id.second_games_buttons, R.id.second_games_button_best,
						R.id.second_games_button_new,
						R.id.second_games_button_rank },
				{ R.id.second_life_buttons, R.id.second_life_button_best,
						R.id.second_life_button_new,
						R.id.second_life_button_rank },
				{ R.id.second_sociality_buttons,
						R.id.second_sociality_button_best,
						R.id.second_sociality_button_new,
						R.id.second_sociality_button_rank },
				{ R.id.second_system_buttons, R.id.second_system_button_best,
						R.id.second_system_button_new,
						R.id.second_system_button_rank },
				{ R.id.second_business_buttons,
						R.id.second_business_button_best,
						R.id.second_business_button_new,
						R.id.second_business_button_rank },
				{ R.id.second_entertainment_buttons,
						R.id.second_entertainment_button_best,
						R.id.second_entertainment_button_new,
						R.id.second_entertainment_button_rank } 
						};
		for (int i = 0; i < flipperId.length; i++) {
			LinearLayout buttonLayout = (LinearLayout) findViewById(flipperId[i][0]);
			
			Button bestButton = (Button) this.findViewById(flipperId[i][1]);
			Button newButton = (Button) this.findViewById(flipperId[i][2]);
			Button rankButton = (Button) this.findViewById(flipperId[i][3]);

			newButton.setOnClickListener(new ButtonClickListener(buttonLayout,
					BUTTON_NEW));
			bestButton.setOnClickListener(new ButtonClickListener(buttonLayout,
					BUTTON_BEST));
			rankButton.setOnClickListener(new ButtonClickListener(buttonLayout,
					BUTTON_RANK));
		}
		
		int[] filterId = new int[] { R.id.second_games_filter,
				R.id.second_life_filter, R.id.second_system_filter,
				R.id.second_business_filter, R.id.second_entertainment_filter,
				R.id.second_sociality_filter };
		for (int i = 0; i < filterId.length; i++) {
			ImageButton secondFilter = (ImageButton) findViewById(filterId[i]);
			secondFilter.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					showDialog(DIALOG_FILTER);
				}
			});
		}
		
		mGestureDetector = new GestureDetector(this);

		setGestureListener(mViewFlipper);
		for (ListView tempView : mViewMap.values()){
			setGestureListener(tempView);
		}

	}

	private void setGestureListener(View v) {
		v.setOnTouchListener(this);
		/*
		 * v.setOnTouchListener(new OnTouchListener(){ public boolean
		 * onTouch(View v, MotionEvent event){
		 * mGestureDetector.onTouchEvent(event); return false; } });
		 */
	}

	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event);
	}

	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return true;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	class ScrollClickListener implements OnClickListener {

		public ScrollClickListener(int index) {
			mIdex = index;
		}

		public void onClick(View v) {
			SetButtonImage(mCurrIndex, false);
			mCurrIndex = mIdex;
			SetButtonImage(mCurrIndex, true);
			mViewFlipper.setDisplayedChild(mIdex);
		}

		private int mIdex;
	};

	private void InitScrollViewButton() {
		mButton_Home = (ImageButton) this.findViewById(R.id.button_homepage);
		mButton_Home.setOnClickListener(new ScrollClickListener(BTN_INDEX));

		mButton_Games = (ImageButton) this.findViewById(R.id.button_games);
		mButton_Games.setOnClickListener(new ScrollClickListener(BTN_GAME));

		mButton_Entertainment = (ImageButton) this
				.findViewById(R.id.button_entertainment);
		mButton_Entertainment.setOnClickListener(new ScrollClickListener(
				BTN_ENTER));

		mButton_Sociality = (ImageButton) this
				.findViewById(R.id.button_sociality);
		mButton_Sociality.setOnClickListener(new ScrollClickListener(
				BTN_SNS));

		mButton_Life = (ImageButton) this.findViewById(R.id.button_life);
		mButton_Life.setOnClickListener(new ScrollClickListener(BTN_MEDIA));

		mButton_Business = (ImageButton) this
				.findViewById(R.id.button_business);
		mButton_Business.setOnClickListener(new ScrollClickListener(
				BTN_OFFICE));

		mButton_System = (ImageButton) this.findViewById(R.id.button_system);
		mButton_System.setOnClickListener(new ScrollClickListener(BTN_SYS));

		mNavigateButtons = (HorizontalScrollView) this
				.findViewById(R.id.navigate_view);
		mNavigateButtons.setSmoothScrollingEnabled(true);
		SetButtonImage(mCurrIndex, true);

	}

	private void showNext() {
		SetButtonImage(mCurrIndex, false);
		this.mCurrIndex++;
		SetButtonImage(mCurrIndex, true);
		if (mCurrIndex >= BTN_MEDIA)
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mNavigateButtons.smoothScrollTo(
							mNavigateButtons.getRight(),
							mNavigateButtons.getBottom());
				}
			});

		mViewFlipper.showNext();
	}

	public boolean haveMenu() {
		return true;
	}

	private void showPrev() {
		SetButtonImage(mCurrIndex, false);
		this.mCurrIndex--;
		if (mCurrIndex < BTN_MEDIA)
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mNavigateButtons.smoothScrollTo(mNavigateButtons.getLeft(),
							mNavigateButtons.getBottom());
				}
			});
		// mNavigateButtons.smoothScrollTo(mNavigateButtons.getLeft(),
		// mNavigateButtons.getBottom());
		SetButtonImage(mCurrIndex, true);
		mViewFlipper.showPrevious();
	}

	private void SetButtonImage(int index, boolean isPressed) {
		switch (index) {
		case BTN_INDEX:
			if (isPressed){
				mButton_Home.setImageResource(R.drawable.word_homepageon);
				mCurrentType = AndroidSWInfoService.CLASS_ID_INDEX;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_Home.setImageResource(R.drawable.word_homepage);
			break;

		case BTN_GAME:
			if (isPressed){
				mButton_Games.setImageResource(R.drawable.word_gameson);
				mCurrentType = AndroidSWInfoService.CLASS_ID_GAME;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_Games.setImageResource(R.drawable.word_games);
			break;

		case BTN_ENTER:
			if (isPressed){
				mButton_Entertainment.setImageResource(R.drawable.word_yuleon);
				mCurrentType = AndroidSWInfoService.CLASS_ID_ENTER;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_Entertainment.setImageResource(R.drawable.word_yule);
			break;

		case BTN_SNS:
			if (isPressed){
				mButton_Sociality.setImageResource(R.drawable.word_networkon);
				mCurrentType = AndroidSWInfoService.CLASS_ID_SNS;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_Sociality.setImageResource(R.drawable.word_network);
			break;

		case BTN_MEDIA:
			if (isPressed){
				mButton_Life.setImageResource(R.drawable.word_liveon);
				mCurrentType = AndroidSWInfoService.CLASS_ID_MEDIA;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_Life.setImageResource(R.drawable.word_live);
			break;

		case BTN_OFFICE:
			if (isPressed){
				mButton_Business.setImageResource(R.drawable.word_businesson);
				mCurrentType = AndroidSWInfoService.CLASS_ID_OFFICE;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_Business.setImageResource(R.drawable.word_business);
			break;

		case BTN_SYS:
			if (isPressed){
				mButton_System.setImageResource(R.drawable.word_systemon);
				mCurrentType = AndroidSWInfoService.CLASS_ID_SYS;
				mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
			}
			else
				mButton_System.setImageResource(R.drawable.word_system);
			break;

		default:
			break;
		}

	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		final int FLING_MIN_DISTANCE = 150, FLING_MIN_VELOCITY = 250;
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_left_in));
			mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_left_out));

			if (mViewFlipper.getCurrentView().getId() != R.id.flipper_system)
				showNext();
			//if (DownloadSoftwareAction.isEmpty())
				return true;

		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_right_in));
			mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_right_out));

			if (mViewFlipper.getCurrentView().getId() != R.id.flipper_home)
				showPrev();
			//if (DownloadSoftwareAction.isEmpty())
				return true;
		}
		return false;
	}

	
	class ListViewScrollListener implements OnScrollListener{
		
		private class DownloadTask extends AsyncTask<String,Void,String>{
			private ListView mListView;
			private ApkPackageAdapter mAdapter;
			public DownloadTask(ListView view, ApkPackageAdapter adapter){
				mListView = view;
				mAdapter = adapter;
			}
			@Override
			protected String doInBackground(String... params) {
				List<APKListItem> apklist = mAdapter.getCurrApkList();
				AndroidSWInfoService.loadNextPage(apklist,
						AndroidSWInfoService.CLASS_ID_INDEX,
						AndroidSWInfoService.SORT_ID_BEST);
				((ScreenHome)ScreenHome.mContext).getHandler().post(new Runnable() {                         
					public void run() {                             
						mAdapter.notifyDataSetChanged();  
						mListView.setSelection(mLastItem);                    
						}                     
					});   
				return null;
			}			
		}
		private int mLastItem = 0;
		private int mType;

		public ListViewScrollListener(int type) {
			mType = type;
		}
		private void loadData(ApkPackageAdapter apkAdapter, ListView view){
			if(apkAdapter == null) return;
			Log.i("ScreenHome", "mLastItem is "+mLastItem +" apkAdapter size is "+ apkAdapter.getCount());
			if(mLastItem>= apkAdapter.getCount()){
				new DownloadTask(view, apkAdapter).execute();					
			}			
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			ApkPackageAdapter apkAdapter = null;
			if (mType == BTN_INDEX) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_INDEX).getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_INDEX));
			} else if (mType == BTN_GAME) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_GAME).getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_GAME));
			} else if (mType == BTN_OFFICE) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_OFFICE).getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_OFFICE));
			} else if (mType == BTN_MEDIA) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_MEDIA).getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_MEDIA));
			} else if (mType == BTN_SNS) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_SNS).getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_SNS));
			} else if (mType == BTN_SYS) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_SYS).getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_SYS));
			} else if (mType == BTN_ENTER) {
				apkAdapter = (ApkPackageAdapter) mViewMap.get(AndroidSWInfoService.CLASS_ID_ENTER)
						.getAdapter();
				loadData(apkAdapter, mViewMap.get(AndroidSWInfoService.CLASS_ID_ENTER));
			}

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			Log.i("ScreenHome","onScroll listener lastItem:" +mLastItem 
					+"firstVisibleItem" + firstVisibleItem +"visibleItemCount " +visibleItemCount);
			mLastItem = firstVisibleItem + visibleItemCount;
		}

	}

	class ButtonClickListener implements OnClickListener {

		public ButtonClickListener(LinearLayout layout, int index) {
			mLayout = layout;
			mButtonType = index;
		}

		public void onClick(View v) {
			
			Log.i("second button","type="+mButtonType);
			switch (mButtonType) {
			case BUTTON_NEW:
				if (!mCurrentSort.equals(AndroidSWInfoService.SORT_ID_NEW)){
					mCurrentSort = AndroidSWInfoService.SORT_ID_NEW;
					mLayout.setBackgroundResource(R.drawable.second_new);
					ApkPackageAdapter apkAdapter = (ApkPackageAdapter)ScreenHome.mContext.mViewMap.get(mCurrentType).getAdapter();
					apkAdapter.setCurrApkList(AndroidSWInfoService.getAndroidSWList(
							mCurrentType,
							mCurrentSort, 0), mCurrentType,mCurrentSort);
					apkAdapter.notifyDataSetChanged();
				}
				break;
			case BUTTON_BEST:
				if (!mCurrentSort.equals(AndroidSWInfoService.SORT_ID_BEST)){
					mCurrentSort = AndroidSWInfoService.SORT_ID_BEST;
					mLayout.setBackgroundResource(R.drawable.second_best);
					ApkPackageAdapter apkAdapter = (ApkPackageAdapter)ScreenHome.mContext.mViewMap.get(mCurrentType).getAdapter();
					apkAdapter.setCurrApkList(AndroidSWInfoService.getAndroidSWList(
							mCurrentType,
							mCurrentSort, 0),mCurrentType,mCurrentSort);
					apkAdapter.notifyDataSetChanged();
				}
				break;
			case BUTTON_RANK:
				if (!mCurrentSort.equals(AndroidSWInfoService.SORT_ID_RANK)){
					mCurrentSort = AndroidSWInfoService.SORT_ID_RANK;
					mLayout.setBackgroundResource(R.drawable.second_rank);
					ApkPackageAdapter apkAdapter = (ApkPackageAdapter)ScreenHome.mContext.mViewMap.get(mCurrentType).getAdapter();
					apkAdapter.setCurrApkList(AndroidSWInfoService.getAndroidSWList(
							mCurrentType,
							mCurrentSort, 0),mCurrentType,mCurrentSort);
					apkAdapter.notifyDataSetChanged();
				}
				break;
			}

		}

		private int mButtonType;
		private LinearLayout mLayout;
	}
	
	class FilterListener implements AdapterView.OnItemClickListener {
		private String[] mSubTypeName;
		
		public FilterListener(String[] subType){
			mSubTypeName = subType;
		}
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Log.i("log","subType="+mSubTypeName[position]);
		}

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			new AlertDialog.Builder(this)
					.setIcon(R.drawable.icon)
					.setTitle(R.string.quittitle)
					.setMessage(R.string.quitmessage)
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									finish();
								}
							}).show();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		System.exit(0);
		// android.os.Process.killProcess(android.os.Process.myPid());
	}
	
	class MessageHandler extends Handler {
		
		ProgressBar progress = null;
    	Button down = null;
    	Button cancel = null;
		
        public MessageHandler(Looper looper) {
            super(looper);
        }
        
        private boolean findViews(int id){
        	List<APKListItem> list = AndroidSWInfoService.getAndroidSWList(ScreenHome.mCurrentType, ScreenHome.mCurrentSort, 0);
        	for (int i=0;i<list.size();i++){
        		APKListItem item = list.get(i);
        		if (item.getID() == id){
        			ListView currentView = ScreenHome.mViewMap.get(ScreenHome.mCurrentType);
        			
        			View itemView = null;
        			
        			if (ScreenHome.mCurrentType == AndroidSWInfoService.CLASS_ID_INDEX)
        				itemView = (View)currentView.getChildAt(i+1-currentView.getFirstVisiblePosition());
        			else 
        				itemView = (View)currentView.getChildAt(i-currentView.getFirstVisiblePosition());
        			
        			if (itemView!=null){
	        			progress = (ProgressBar)itemView.findViewById(R.id.package_download_progress);
	        			down = (Button)itemView.findViewById(R.id.package_download);
	        			cancel = (Button)itemView.findViewById(R.id.package_cancel);
	        			return true;
        			}
        			else {
        				return false;
        			}
        		}
        	}

        	return false;
        }

        @Override
        public void handleMessage(Message msg) {
        	String msgStr = (String)msg.obj;
        	MyLog.info(TAG, "handleMessage msgStr="+msgStr);
        	if (msgStr.startsWith("startDownload")){
        		String[] temp = msgStr.split("/");
        		if (findViews(Integer.parseInt(temp[1]))){
        			progress.setVisibility(View.VISIBLE);
        			down.setVisibility(View.GONE);
        			cancel.setVisibility(View.VISIBLE);
        		}
        	}
        	else if (msgStr.startsWith("endDownload")){
        		String[] temp = msgStr.split("/");
        		if (findViews(Integer.parseInt(temp[1]))){
        			progress.setVisibility(View.GONE);
        			down.setVisibility(View.VISIBLE);
        			cancel.setVisibility(View.GONE);
        		}
        	}
        	else if (msgStr.startsWith("downloading")){
        		
        		String[] temp = msgStr.split("/");
        		if (findViews(Integer.parseInt(temp[2]))){
        			progress.setVisibility(View.VISIBLE);
        			down.setVisibility(View.GONE);
        			cancel.setVisibility(View.VISIBLE);
        			progress.setProgress(Integer.parseInt(temp[1]));
        		}
        		//mDownloadingProgress.setSecondaryProgress(Integer.parseInt(temp[1]));
        	}
        	else if (msgStr.startsWith("cancelDownload")){
        		String[] temp = msgStr.split("/");
        		if (findViews(Integer.parseInt(temp[1]))){
        			progress.setVisibility(View.GONE);
        			down.setVisibility(View.VISIBLE);
        			cancel.setVisibility(View.GONE);

        		}
        	}
        }

    }
}
